<template>
  <van-index-bar :index-list="cityIndexList">
    <div v-for="item in clityList" :key="item.type">
      <van-index-anchor :index="item.type" />
      <van-cell v-for="city in item.list" :key="city.cityId" :title="city.name" @click="handelChange(city)" />
    </div>
  </van-index-bar>
</template>

<script>
import { getCity } from '../api/film'
import { mapMutations } from 'vuex'
export default {
  name: 'CityView',
  data() {
    return {
      clityList: []
    }
  },
  computed: {
    cityIndexList() {
      return this.clityList.map(item => item.type)
    }
  },
  methods: {
    ...mapMutations('City', ['changeCityData']),
    async getCity() {
      const { data } = await getCity()
      this.handelCityData(data.data.cities)
    },
    handelCityData(data) {
      const letterArr = []
      for (let code = 65; code < 91; code++) {
        letterArr.push(String.fromCharCode(code))
      }
      const newCites = []
      letterArr.forEach(letter => {
        const list = data.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        if (list.length) {
          newCites.push({
            type: letter,
            list
          })
        }
      })
      this.clityList = newCites
    },
    handelChange(city) {
      this.changeCityData(city)
      this.$router.back()
    }
  },
  mounted() {
    this.getCity()
  }
}
</script>

<style></style>